<template>
  <div class="e-search-form" v-loading="loading">
    <eContentWrap>
      <template #title>
        <!-- <div class="w-full flex justify-between items-center"> -->
        <div>
          <span class="search-title">{{ title || '查询条件' }}</span>
        </div>
        <div class="flex items-center">
          <template v-if="showCollapse">
            <e-button @click="handleCollapse" v-if="isCollapse">展开</e-button>
            <e-button class="ml-2" @click="handleCollapse" v-if="!isCollapse">收起</e-button>
          </template>
          <e-button class="ml-2" @click="openFilterSearch" v-if="uniqueKey">筛选设置</e-button>
          <e-button class="ml-2" @click="handleReset">重置</e-button>
          <e-button class="ml-2" type="primary" @click="handleSearch" v-hasPermi="searchPermission"
            >搜索</e-button
          >
        </div>
        <!-- </div> -->
      </template>
      <div :class="{ 'is-collapse': isCollapse }">
        <el-form
          :model="queryForm"
          label-width="120px"
          class="flex flex-wrap items-center"
          label-position="top"
        >
          <template v-for="(item, index) in visibleColumns" :key="index">
            <el-form-item :label="item.label" v-if="item.isFilter">
              <template #label>
                {{ item.label }}
                <span style="color: rgb(67 191 7)" class="operator" v-if="operatorMap[item.prop]">{{
                  operatorOptions[operatorMap[item.prop]]
                }}</span>
                <span
                  style="color: rgb(241 8 8)"
                  class="operator"
                  v-else-if="operatorExcludeMap[item.prop]"
                  >{{ operatorOptions[operatorExcludeMap[item.prop]] }}</span
                >
              </template>
              <div
                class="query-item-wrapper"
                :class="{ 'width-full': item.filterConfig.hiddenFilter }"
              >
               
                <!-- 远程选择 -->
                <e-remote-select
                  v-model="queryForm[item.prop]"
                  v-if="item.filterConfig.type === 'remoteSelect'"
                  :ref="(el) => (remoteSelectRefs[item.prop] = el)"
                  :placeholder="item.filterConfig.placeholder"
                  :initOptions="item.filterConfig.options"
                  :showFiled="item.filterConfig.showFiled"
                  :query-api="item.filterConfig.queryApi"
                  :fetch-value-api="item.filterConfig.fetchValueApi"
                  :isLoadMore="item.filterConfig.isLoadMore"
                  :limit="item.filterConfig.limit"
                  clearable
                  @update:value-model="item.filterConfig.handleUpdateValueModel"
                  @change="removeOperator(item.prop)"
                  v-bind="item.filterConfig.attrs"
                  :isSearch="false"
                  />
                <!-- 会导致远程选择组件的valueModel值为空，无法正常回填 -->
                <!-- :isSearch="item.prop === 'creator' ? false : true" -->

                <el-select
                  v-model="queryForm[item.prop]"
                  v-else-if="item.filterConfig.type === 'select'"
                  :max-collapse-tags="1"
                  :placeholder="item.filterConfig.placeholder"
                  :multiple="item.filterConfig.multiple"
                  allow-clear
                  collapse-tags
                  clearable
                  style="width: 100%"
                  @change="removeOperator(item.prop)"
                >
                  <el-option
                    v-for="option in item.filterConfig.options"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  />
                </el-select>

                <el-date-picker
                  v-model="queryForm[item.prop]"
                  v-else-if="item.filterConfig.type === 'date'"
                  :type="item.filterConfig.dateType || 'date'"
                  :placeholder="item.filterConfig.placeholder"
                  :format="item.filterConfig.format || 'YYYY-MM-DD'"
                  :value-format="item.filterConfig.valueFormat || 'YYYY-MM-DD'"
                  style="width: 100%"
                  @change="removeOperator(item.prop)"
                />

                <el-date-picker
                  v-else-if="item.filterConfig.type === 'dateRange'"
                  v-model="queryForm[item.prop]"
                  format="YYYY-MM-DD"
                  :value-format="item.filterConfig.valueFormat || 'YYYY-MM-DD'"
                  type="daterange"
                  :default-time="[new Date(2000, 0, 1, 0, 0, 0), new Date(2000, 0, 1, 23, 59, 59)]"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  style="width: 100%"
                  @change="removeOperator(item.prop)"
                />
                <el-switch
                  v-else-if="item.prop === 'isOnlySelf'"
                  v-model="queryForm.isOnlySelf"
                  :active-value="1"
                  :inactive-value="0"
                  @change="handleSearch"
                />
                <el-switch
                  v-else-if="item.filterConfig.type === 'switch'"
                  v-model="queryForm[item.prop]"
                  :active-value="item.filterConfig.activeValue || 1"
                  :inactive-value="item.filterConfig.inactiveValue || 0"
                />
                <el-input
                  v-model="queryForm[item.prop]"
                 v-else
                  :placeholder="item.filterConfig.placeholder"
                  @change="removeOperator(item.prop)"
                  v-bind="item.filterConfig.attrs"
                />
                <el-button
                  v-if="!item.filterConfig.hiddenFilter"
                  @click="
                    openAdvancedFilter(
                      item.prop,
                      operatorMap[item.prop],
                      operatorExcludeMap[item.prop]
                    )
                  "
                >
                  <el-icon><Filter /></el-icon>
                </el-button>
              </div>
              <!-- 添加高级筛选图标 -->
              <eAdvancedFilter
                v-if="!item.filterConfig.hiddenFilter"
                :ref="(el) => (advancedFilterRefs[item.prop] = el)"
                :title="`${item.label}高级筛选`"
                :field="item.prop"
                :filterConfig="item.filterConfig"
                :searchValue="queryForm[item.prop]"
                @filter-change="handleFilterChange"
              />
            </el-form-item>
          </template>
        </el-form>
      </div>
      <div class="search-btn"></div>
    </eContentWrap>
    <EFilterSearch
      ref="filterSearchRef"
      :columns="props.columns"
      :unique-key="props.uniqueKey"
      @confirm="handleFilterConfirm"
      :saveSettingFunc="saveSettingFunc"
    />
  </div>
</template>
<script lang="ts" setup>
  import { ref, nextTick, onMounted, watch, computed } from 'vue'
  import { propTypes } from '@/utils/propTypes'
  import { Filter } from '@element-plus/icons-vue'
  import { useAdvancedFilter } from '@/components/eAdvancedFilter/src/type'
  import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
  // import { getListSetting } from '@/api/system/user'
  import { setComponentsState, getComponentsState } from '@/utils/qiankunState'
  import { useRoute } from 'vue-router'
import { columnsType } from './type'

  defineOptions({ name: 'ESearchForm' })
  const props = defineProps({
    title: propTypes.string.def(''),
    columns: propTypes.array.def([]),
    isShowCollapse: propTypes.bool.def(true),
    autoSearch: propTypes.bool.def(true),
    columnNum: propTypes.number.def(4),
    searchPermission: propTypes.array.def([]),
    uniqueKey: propTypes.string.def(''),
    showCollapse: propTypes.bool.def(true),
    getSettingFunc: propTypes.func.def(() => {}),
    saveSettingFunc: propTypes.func.def(() => {}),
  })

  const isCollapse = ref(false)
  // 获取当前用户信息
  const { wsCache } = useCache()
  const userInfo =wsCache?.get(CACHE_KEY.USER)?.user??{}
  const emit = defineEmits(['search', 'reset'])
  // 列配置
  const queryForm = ref<Recordable>({})
    const filterSearchRef = ref()
  // 联想下拉组件引用
  const remoteSelectRefs = ref<Recordable>({})
  // 使用抽取出的高级筛选逻辑
  const { advancedFilterRefs, openAdvancedFilter } = useAdvancedFilter()
  // 高级筛选回填条件包含映射
  const operatorMap = ref<{ [key: string]: string }>({})
  // 高级筛选回填条件排除映射
  const operatorExcludeMap = ref<{ [key: string]: string }>({})
  // 显示的列配置
  const visibleColumns = ref<columnsType[]>([])
  // 获取所有字段包含/排除条件
  const getIncludeExclude = () => {
    let includeMap: { [key: string]: { [key: string]: any }[] } = {}
    let excludeMap: { [key: string]: { [key: string]: any }[] } = {}
    Object.keys(advancedFilterRefs.value).forEach((key) => {
      includeMap[key] = advancedFilterRefs.value[key]
        ?.getIncludeRows()
        .map((item: any, index: number) => {
          let result = { ...item }
          if (['range', 'not_range'].includes(item.operator)) {
            result.value = [result.value1, result.value2]
          }
          if (!index) {
            delete result.logicType
          }
          return result
        })
      excludeMap[key] = advancedFilterRefs.value[key]
        ?.getExcludeRows()
        .map((item: any, index: number) => {
          let result = { ...item }
          if (['range', 'not_range'].includes(item.operator)) {
            result.value = [result.value1, result.value2]
          }
          if (!index) {
            delete result.logicType
          }
          return result
        })
    })
    return { includeMap, excludeMap }
  }


  // 是否正在初始化
  const isInitializing = ref<boolean>(false)
  const handleSearch = () => {
    if (isInitializing.value) return
    nextTick(() => {
      emit('search', { ...getParams() })
    })
  }



  const operatorOptions: { [key: string]: string } = {
    eq: '=',
    neq: '≠',
    gt: '>',
    gte: '≥',
    lt: '<',
    lte: '≤',
    range: '[]',
    not_range: '][',
    like: '≈'
  }

  // 设置所有字段包含/排除条件
  const setIncludeExclude = (prop) => {
    let item: any = visibleColumns.value.find((item) => item.prop === prop)
    Object.keys(advancedFilterRefs.value).forEach((key) => {
      if (key === prop) {
        let includeRows = advancedFilterRefs.value[key]?.getIncludeRows() || []
        let excludeRows = advancedFilterRefs.value[key]?.getExcludeRows() || []
        if (includeRows.length > 0) {
          if (!queryForm.value[prop]) {
            // 查询条件为空
            includeRows = includeRows.slice(1) || []
          } else {
            // 查询条件不为空
            includeRows[0].value = queryForm.value[prop]
            includeRows[0].value1 = null
            includeRows[0].value2 = null
            if (['not_range', 'range'].includes(includeRows[0].operator)) {
              // 操作符为范围/范围外
              if (queryForm.value[prop].includes('~')) {
                // 包含~，则将value1和value2设置为范围
                includeRows[0].value1 = queryForm.value[prop].split('~')[0]
                includeRows[0].value2 = queryForm.value[prop].split('~')[1]
                includeRows[0].value = queryForm.value[prop].split('~')
              } else {
                // 否则将操作符设置为等于
                includeRows[0].operator =
                  item.filterConfig.defaultOperator ||
                  (item.filterConfig.type === 'input' ? 'like' : 'eq')
              }
            }
          }
          advancedFilterRefs.value[key].setIncludeRows(includeRows)
        } else if (excludeRows.length > 0) {
          if (!queryForm.value[prop]) {
            // 查询条件为空
            excludeRows = excludeRows.slice(1) || []
          } else {
            // 查询条件不为空
            excludeRows[0].value = queryForm.value[prop]
            excludeRows[0].value1 = null
            excludeRows[0].value2 = null
            if (['not_range', 'range'].includes(excludeRows[0].operator)) {
              if (queryForm.value[prop].includes('~')) {
                // 包含~，则将value1和value2设置为范围
                excludeRows[0].value1 = queryForm.value[prop].split('~')[0]
                excludeRows[0].value2 = queryForm.value[prop].split('~')[1]
                includeRows[0].value = queryForm.value[prop].split('~')
              } else {
                // 否则将操作符设置为等于
                excludeRows[0].operator =
                  item.filterConfig.defaultOperator ||
                  (item.filterConfig.type === 'input' ? 'like' : 'eq')
              }
            }
          }
          advancedFilterRefs.value[key]?.setExcludeRows(excludeRows)
        } else if (queryForm.value[prop]) {
          advancedFilterRefs.value[key]?.setIncludeRows([
            {
              operator:
                item.filterConfig.defaultOperator ||
                (item.filterConfig.type === 'input' ? 'like' : 'eq'),
              value: queryForm.value[prop],
              value1: null,
              value2: null,
              isValid: true
            }
          ])
        }
      }
    })
  }
  // 编辑查询条件后,如果值为空，则删除operatorMap中对应的prop，
  // 如果不为空，且operator是range/not_range,则判断输入项是否包含~，
  // 如果不包含~，则将operator设置为eq
  const removeOperator = (prop) => {
    setIncludeExclude(prop)
    let item: any = visibleColumns.value.find((item) => item.prop === prop)
    if (!queryForm.value[prop] || queryForm.value[prop]?.length === 0) {
      delete operatorMap.value[prop]
      delete operatorExcludeMap.value[prop]
    } else if (
      operatorMap.value[prop] &&
      ['range', 'not_range'].includes(operatorMap.value[prop])
    ) {
      if (!queryForm.value[prop].includes('~')) {
        operatorMap.value[prop] =
          item.filterConfig.defaultOperator || (item.filterConfig.type === 'input' ? 'like' : 'eq')
      }
    } else if (
      operatorExcludeMap.value[prop] &&
      ['range', 'not_range'].includes(operatorExcludeMap.value[prop])
    ) {
      if (!queryForm.value[prop].includes('~')) {
        operatorExcludeMap.value[prop] =
          item.filterConfig.defaultOperator || (item.filterConfig.type === 'input' ? 'like' : 'eq')
      }
    } else if (!operatorMap.value[prop] && !operatorExcludeMap.value[prop]) {
      operatorMap.value[prop] =
        item.filterConfig.defaultOperator || (item.filterConfig.type === 'input' ? 'like' : 'eq')
    }
  }

  // 高级筛选管理弹窗确认时，回填数据.
  // flag=true时，表示高级筛选管理弹窗确认触发查询，flag=false时，表示高级筛选管理弹窗关闭不触发查询
  const handleFilterChange = (filters: any, flag: boolean) => {
    let filterInclude: any = filters.include.find((filter: any) => filter.value)
    let filterExclude: any = filters.exclude.find((filter: any) => filter.value)
    queryForm.value[filters.field] = ''
    if (filterInclude) {
      queryForm.value[filters.field] = filterInclude?.value || ''
      operatorMap.value[filters.field] = filterInclude?.operator || ''
      delete operatorExcludeMap.value[filters.field]
    } else if (filterExclude) {
      queryForm.value[filters.field] = filterExclude?.value || ''
      operatorExcludeMap.value[filters.field] = filterExclude?.operator || ''
      delete operatorMap.value[filters.field]
    } else {
      // 高级筛选管理弹窗内容为空时，清除对应查询条件
      delete queryForm.value[filters.field]
      delete operatorMap.value[filters.field]
      delete operatorExcludeMap.value[filters.field]
    }
    if (flag) {
      handleSearch()
    }
  }



  // 在输入创建人时清空只查询自己的勾选
  watch(
    () => [queryForm.value.creator, operatorMap.value.creator],
    ([creator, creatorOperator]) => {
      let creatorColumn: columnsType = visibleColumns.value.find(
        (item: columnsType) => item.prop === 'creator'
      ) as columnsType
      let showSelf: boolean = visibleColumns.value.some(
        (item: columnsType) => item.prop === 'isOnlySelf'
      )
      if (creatorColumn?.isFilter) {
        setIncludeExclude('creator')
        if (showSelf) {
          if (creator) {
            if (creator === userInfo.id && creatorOperator !== 'neq') {
              queryForm.value.isOnlySelf = 1
            } else {
              queryForm.value.isOnlySelf = 0
            }
          } else {
            queryForm.value.isOnlySelf = 0
          }
        }
      }
    },
    { immediate: true }
  )

  // 在勾选只查询自己时清空创建人
  watch(
    () => queryForm.value.isOnlySelf,
    (isOnlySelf) => {
      if (isOnlySelf) {
        queryForm.value.creator = userInfo.id
        operatorMap.value.creator = 'eq'
        advancedFilterRefs.value['creator']?.setIncludeRows([
          {
            operator: 'eq',
            value: userInfo.id,
            value1: null,
            value2: null,
            isValid: true
          }
        ])
      } else if (queryForm.value.creator === userInfo.id && operatorMap.value.creator !== 'neq') {
        queryForm.value.creator = ''
        operatorMap.value.creator = ''
      }
    }
  )



  const handleReset = () => {
    operatorMap.value = {}
    operatorExcludeMap.value = {}
    queryForm.value = {}
    visibleColumns.value
      .filter((item) => item.isFilter)
      .forEach((item) => {
        if (
          item.filterConfig &&
          (item.filterConfig.multiple || item.filterConfig.type === 'dateRange')
        ) {
          queryForm.value[item.prop] = []
          // } else if (item.prop === 'creator' && queryForm.value.isOnlySelf) {
        } else if (queryForm.value.isOnlySelf) {
          queryForm.value[item.prop] = userInfo.id
          operatorMap.value[item.prop] = 'eq'
        } else if (item.filterConfig.type === 'remoteSelect') {
          // 清空联想下拉组件的值
          remoteSelectRefs.value[item.prop]?.clearValue()
          // 设置默认值
          queryForm.value[item.prop] = item.filterConfig.default || ''
        } else {
          queryForm.value[item.prop] = item.filterConfig.default || ''
        }
      })
    nextTick(() => {
      // 等待显示字段更新后再清空对应的高级筛选
      for (const item in advancedFilterRefs.value) {
        const filterRef = advancedFilterRefs.value[`${item}`]
        if (filterRef && typeof filterRef.openDialog === 'function') {
          filterRef.clearFilter()
        }
      }
      nextTick(() => {
        // 等待显示字段更新后再重置查询条件
        visibleColumns.value.forEach((item) => {
          setIncludeExclude(item.prop)
        })
        handleSearch()
        emit('reset', queryForm.value)
      })
    })
  }
  const openFilterSearch = () => {
    console.log('visibleColumns.value=>', filterSearchRef.value)
    filterSearchRef.value?.open(visibleColumns.value)
  }
  // 筛选字段确认时，重置查询条件
  const handleFilterConfirm = (columns: columnsType[]) => {
    visibleColumns.value = [...columns].map((item) => {
      return { ...item }
    })
    // 修改筛选字段后，重置查询条件
    handleReset()
  }
  const handleCollapse = () => {
    isCollapse.value = !isCollapse.value
  }

  // 从缓存或者接口获取表格配置
  const loading = ref(false)
  const route = useRoute()
  const initVisibleColumns = async () => {
    loading.value = true
    isInitializing.value = true
    let config: columnsType[] = await new Promise((resolve) => {
      /* 不能从缓存中获取，因为没有携带用户信息 */
      // let config = sessionStorage.getItem(props.uniqueKey) // 从缓存获取表格配置
      // if (!config) {
      // 直接从接口获取
      if (props.uniqueKey) {
        props.getSettingFunc?.({
          settingKey: props.uniqueKey
        }).then((res) => {
          console.log('res=>', res)
          if (res?.settingValue) {
            let settingValue: columnsType[] = []
            JSON.parse(res.settingValue).forEach((item: columnsType) => {
              let column: columnsType = props.columns.find(
                (col: columnsType) => col.prop === item.prop
              ) as columnsType
              if (column) {
                settingValue.push({ ...column, isFilter: item?.isFilter })
              }
            })
            resolve(settingValue) // 会丢失方法
          } else {
            resolve([...props.columns].map((col: columnsType) => ({ ...col })))
          }
        })
      } else {
        resolve([...props.columns].map((col: columnsType) => ({ ...col })))
      }
      // } else {
      //   resolve(JSON.parse(config))
      // }
    })
    visibleColumns.value = config
    nextTick(() => {
      // 初始化查询条件
      let stateQueryForm = getComponentsState(route.fullPath)?.queryForm || {}
      let stateIncludeExclude = getComponentsState(route.fullPath)?.includeExclude || {}
      visibleColumns.value.forEach((item) => {
        queryForm.value[item.prop] =
          stateQueryForm[item.prop] !== undefined
            ? stateQueryForm[item.prop]
            : item.isFilter
              ? item.filterConfig?.default
              : ''
      })

      // 等待下一个 tick，确保组件已完全挂载
      nextTick(() => {
        visibleColumns.value.forEach((item) => {
          if (advancedFilterRefs.value[item.prop]) {
            try {
              if (stateIncludeExclude.includeMap?.[item.prop]) {
                advancedFilterRefs.value[item.prop].setIncludeRows(
                  stateIncludeExclude.includeMap[item.prop]
                )
              }
              if (stateIncludeExclude.excludeMap?.[item.prop]) {
                advancedFilterRefs.value[item.prop].setExcludeRows(
                  stateIncludeExclude.excludeMap[item.prop]
                )
              }
            } catch (err) {
              console.error('设置高级筛选条件失败:', err)
            }
          }
        })
        isInitializing.value = false
        if (props.autoSearch) {
          handleSearch() // 初始化查询条件后，触发查询
        }
      })
    })
    loading.value = false
  }
  // 生命周期钩子
  onMounted(() => {
    initVisibleColumns()
  })

  // 构架查询参数：非高级筛选项放在query中
  const getParams = () => {
    // console.log('getIncludeExclude()=>', getIncludeExclude())
    // console.log('queryForm.value=>', queryForm.value)
    let query = { ...queryForm.value }
    // 过滤掉高级筛选项中存在的普通筛选项
    let fieldFilters = [
      ...new Set(
        Object.values(getIncludeExclude())
          .map((item) => Object.keys(item).filter((key) => item[key] && item[key].length))
          .flat()
      )
    ]
    fieldFilters.forEach((item) => {
      delete query[item]
    })

    // 过滤掉 query 中的空值
    Object.keys(query).forEach((key) => {
      if (
        query[key] === '' ||
        query[key] === null ||
        query[key] === undefined ||
        (Array.isArray(query[key]) && query[key].length === 0)
      ) {
        delete query[key]
      }
    })

    // 过滤掉 getIncludeExclude() 中的空值
    const { includeMap, excludeMap } = getIncludeExclude()
    const filteredIncludeMap = {}
    const filteredExcludeMap = {}

    Object.keys(includeMap).forEach((key) => {
      if (includeMap[key] && includeMap[key].length > 0) {
        filteredIncludeMap[key] = includeMap[key]
      }
    })

    Object.keys(excludeMap).forEach((key) => {
      if (excludeMap[key] && excludeMap[key].length > 0) {
        filteredExcludeMap[key] = excludeMap[key]
      }
    })

    return { includeMap: filteredIncludeMap, excludeMap: filteredExcludeMap, ...query }
  }


  // 缓存查询参数
  const params = computed(() => {
    return {
      queryForm: queryForm.value,
      includeExclude: getIncludeExclude()
    }
  })
  // 监听查询参数变化，缓存查询参数
  watch(
    () => params.value,
    (newVal) => {
      if (newVal && !isInitializing.value) {
        setComponentsState(route.fullPath, newVal)
      }
    },
    {
      deep: true
    }
  )
  defineExpose({
    handleSearch,
    handleReset,
    // 获取查询参数
    getParams
  })
</script>
<style lang="scss" scoped>
  .e-search-form {
    margin-bottom: 10px;
    --column-num: v-bind('props.columnNum');
    .search-title {
      font-family: PingFang SC;
      font-size: 18px;
      font-weight: 600;
      line-height: 25.2px;
      text-align: left;
      text-underline-position: from-font;
      text-decoration-skip-ink: none;
      color: #000000;
    }
    :deep(.el-form-item) {
      width: calc(100% / var(--column-num));
    }
    .operator {
      font-size: 16px;
      margin-left: 3px;
      font-weight: 600;
    }
    .query-item-wrapper {
      margin-right: 61px;
      display: flex;
      align-items: center;
      width: 100%;
      :deep(.el-input__wrapper) {
        border-radius: 4px 0 0 4px;
        width: 210px;
      }
      :deep(.el-button) {
        border-radius: 0 4px 4px 0;
        background-color: #f7f8fa;
        color: #bfbfbf;
        border-left: none;
      }
      // el-date-editor--daterange
      :deep(.el-date-editor--daterange) {
        width: 210px !important;
      }
    }
    .width-full {
      :deep(.el-input__wrapper) {
        width: 255px;
      }
      // el-date-editor--daterange
      :deep(.el-date-editor--daterange) {
        width: 255px !important;
      }
    }
    .search-btn {
      display: flex;
      justify-content: flex-end;
      margin-top: 10px;
    }
    .is-collapse {
      max-height: 80px;
      overflow: hidden;
    }
  }
</style>
